<?php

class TokenUserCacheModel
{
    private $tokenUserKeyPrefix =   'TU/';
    private $jpushSetModel;
	private $diaryListCacheModel;
	
    function __construct()
    {
    	$this->jpushSetModel          =    new JpushSetModel();
    	$this->diaryListCacheModel    =    new DiaryListCacheModel();
    }   

    public function getUserToken($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'TUM001';
            return  FALSE;
        }

        $uid = $info['uid'];
        $result = $this->diaryListCacheModel->getUserToken($uid);
        // token最后读取时间大于1天则更新
        if ((AC::SERVER_TIME - intval($result['last_time'])) > 86400 ){
                $this->diaryListCacheModel->updateTokenTime($uid);
        }
        
        if(empty($result)){
	        $key    =   $this->tokenUserKeyPrefix . $uid;
	        $token =   Storage::getData($key);
	        // push时间
	        $pushInfo = $this->jpushSetModel->getPushInfo(array('uid'=>$uid));
		if(!empty($pushInfo)){
	        	$token['p'] = intval($pushInfo['time']);
		}
	      
	        $result = $this->changeTokenData($token);
	        $this->diaryListCacheModel->addUserToken($uid, $result);
        }
        return  $result;
    }/*}}}*/
    
    public function changeTokenData($data){
        if (empty($data)) return false;
        $token = array();
        $token['uid']   =  strval($data['uid']);
        $token['token'] =  $data['token'];
        $token['last_time'] = AC::SERVER_TIME;
	if (!isset($data['p'])) $data['p']= '';
        $token['p'] = intval($data['p']);
        return $token;
    }
   
    public function makeUserToken($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'TUM001';
            return  FALSE;
        }

        $token  =   md5($info['uid']. AC::SERVER_TIME. rand());
        $ip     =   UK::getClientIp();
        $method =   $info['do'];

        $data   =   array();
        $data['uid']            =   $info['uid'];
        $data['token']          =   $token;
        $data['tokenTime']      =   AC::SERVER_TIME;
        $data['tokenIp']        =   UK::getClientIp();
        $data['tokenMethod']    =   $info['do'];

        $key    =   $this->tokenUserKeyPrefix . $info['uid'];
        $result =   Storage::getData($key);
        if (!empty($result) && $result['uid'] >0){
            $result =   Storage::setData($key, $data);
        }else{
            $result =   Storage::addData($key, $data);
        }
       
        if(!empty($result)){
        	$uid = $info['uid'];
        	$redisToken =  $this->changeTokenData($data);
        	$this->diaryListCacheModel->addUserToken($uid, $redisToken);
        }
        
        if (empty($result)) return  $result;
        else    return  $token;
    }/*}}}*/

}

